<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
require_once (dirname ( __FILE__ ) . "/../../PHPExcel/PHPExcel/Reader/Excel5.php");
class User extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'passport/index' );
			exit ();
		}
	}
	/*
	 * 返回用户列表
	 */
	public function index() {
		$order = $this->input->get ( 'order' );
		$class = $this->uri->segment(4);
    	if(empty($class)){
    		$class=0;
    	}
		$sno = $this->uri->segment(6);
    	if(empty($sno)){
    		$sno=0;
    	}
		$name = $this->uri->segment(8);
    	$name=urldecode($name);//转化为汉字
    	if(empty($name)){
    		$name="empty";
    	}
		if(empty($order)){
    		$order=0;
    	}
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=10;//暂定为10条

		$config['base_url']=site_url('user/index/class/'.$class.'/sno/'.$sno.'/name/'.$name);
		$this->load->model ( 'user_model' );

		if($name=="empty"){// 这里是为了搜索
    		$name=null;
    	}
		// 数据总数
		$config ['total_rows']  = $this->user_model->count_users($class,$name,$sno);
		// $config ['total_rows']=200;
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =9;

		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		// 偏移量
		$offset=intval($this->uri->segment(9));
		$data ['users']=$this->user_model->get_users ($class,$name,$sno,$per_page,$offset,$order);
		$data ['title'] = '用户列表 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'user/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 跳转到余额充值页面
	 */
	public function recharge() {
		$userid=$this->uri->segment(4);
		$this->load->model ( 'user_model' );
		$data['user']=$this->user_model->load($userid);
		$data ['title'] = '余额充值- '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'user/recharge' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 余额充值处理
	 */
	public function rechargeaccount() {
		$userid = $this->input->post ( 'userid' );
		$money= $this->input->post ( 'money' );
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load($userid);
		$newbalance= $money+$user['balance'];
		$newuser = array (
				'balance' => $newbalance
		);
		if($this->user_model->update( $userid, $newuser )){
				return_json ( TRUE, '', '充值成功！账户余额为'.$newbalance.'元');
		}else{
				return_json ( FALSE, '', '充值失败！' );
		}
	}
	/*
	 * 获得学校信息
	 */
	public function getschools() {
		$this->load->model ( 'school_model' );
		$data = $this->school_model->find_all_school ();
		if (! empty ( $data )) {
			return_json ( TRUE, $data, '查询成功！' );
		}
		return_json ( FALSE, '', '查询失败！' );
	}
	/*
	 * 获得年级信息(用于修改个人信息)
	 */
	public function getgrades() {
		$type = $this->input->post ( 'type' );
		$this->load->model ( 'school_model' );
		$data = $this->school_model->find_grade_by_type ($type);
		if (! empty ( $data )) {
			return_json ( TRUE, $data, '查询成功！' );
		}
		return_json ( FALSE, '', '查询失败！' );
	}
	/*
	 * 获得班级信息(用于修改个人信息)
	 */
	public function getclasses() {
		$school = $this->input->post ( 'school' );
		$grade = $this->input->post ( 'grade' );
		$this->load->model ( 'school_model' );
		$data = $this->school_model->find_class_by_school_grade ($school,$grade);
		if (! empty ( $data )) {
			return_json ( TRUE, $data, '查询成功！' );
		}
		return_json ( FALSE, '', '查询失败！' );
	}
	/*
	 * 跳转到添加用户页面
	 */
	public function add() {
		$this->load->model ( 'school_model' );
		$schools = $this->school_model->find_all_school ();
		$data['school'] = $schools;
		$data['title'] = '添加用户 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'user/add');
		$this->load->view ( 'footer');
	}
	/*
	 * 跳转到编辑用户页面
	 */
	public function edit() {
		$userid=$this->uri->segment(4);
		$this->load->model ( 'user_model' );
		$user = $this->user_model->load ( $userid );
		$this->load->model ( 'school_model' );
		$class = $this->school_model->find_class_by_id ($user['class']);
		$schools = $this->school_model->find_all_school ();
		$grades = $this->school_model->find_grade_by_type ($class['type']);
		$classes = $this->school_model->find_class_by_school_grade ($class['schoolid'],$class['gradeid']);
		$data['user'] = $user;
		$data['school'] = $schools;
		$data['grade'] = $grades;
		$data['class'] = $classes;
		$data['title'] = '编辑用户 - '.SYSTEM_NAME;
		$this->load->view ( 'header', $data );
		$this->load->view ( 'user/edit');
		$this->load->view ( 'footer');
	}
	/*
	 * 保存用户资料
	 */
	public function save() {
		$no=$this->input->post ( 'no' );//卡号
		$no2=$this->input->post ( 'no2' );//卡号2
		$sno=$this->input->post ( 'sno' );//学号
		$this->load->model ( 'user_model' );
		if(!empty($no)){
			$temp=$this->user_model->find_by_no ( $no );
			if(!empty($temp)){
				return_json(FALSE,'','卡号1已存在!');
			}
		}
		if(!empty($no2)){
			$temp=$this->user_model->find_by_no ( $no2 );
			if(!empty($temp)){
				return_json(FALSE,'','卡号2已存在!');
			}
		}
		$user = array (
			'username' => $this->input->post ( 'phone' ),
			'phone' => $this->input->post ( 'phone' ),
			'pname' => $this->input->post ( 'pname' ),
			'sname' => $this->input->post ( 'sname' ),
			'class' => $this->input->post ( 'class' ),
			'sno' => $sno,
			'password' => md5 ( substr($sno,-6) . 'jishibao' ),
			'no' => $no,
			'no2' => $no2
		);
		$userid=$this->user_model->create ( $user );
		if(!empty($userid)){
			return_json(TRUE,'','添加成功!');
		}
		return_json(FALSE,'','添加失败!');
	}
	/*
	 * 更新用户资料
	 */
	public function update() {
		$userid = $this->input->post ( 'userid' );
		$no=$this->input->post ( 'no' );//卡号
		$no2=$this->input->post ( 'no2' );//卡号2
		$this->load->model ( 'user_model' );
		if(!empty($no)){
			$temp=$this->user_model->find_by_no ( $no );
			if(!empty($temp)&&$temp['id']!=$userid){
				return_json(FALSE,'','卡号1已存在!');
			}
		}
		if(!empty($no2)){
			$temp=$this->user_model->find_by_no ( $no2 );
			if(!empty($temp)&&$temp['id']!=$userid){
				return_json(FALSE,'','卡号2已存在!');
			}
		}
		$user = array (
			'username' => $this->input->post ( 'phone' ),
			'phone' => $this->input->post ( 'phone' ),
			'pname' => $this->input->post ( 'pname' ),
			'sname' => $this->input->post ( 'sname' ),
			'class' => $this->input->post ( 'class' ),
			'sno' => $this->input->post ( 'sno' ),
			'no' => $no,
			'no2' => $no2
		);
		$this->user_model->update ( $userid, $user );

		return_json(TRUE,'','修改成功!');
	}
	/*
	 * 重置密码
	 */
	public function resetPassword() {
	    $userid = $this->input->post('userid');
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load ( $userid );
		$newuser = array (
			'password' => md5 ( substr($user['sno'],-6) . 'jishibao' )
		);
		$this->user_model->update ( $userid, $newuser );
		return_json(TRUE,'','重置密码成功！');
	}
	/*
	 * 删除用户信息
	 */
	public function delete() {
	    $id = $this->input->post('id');
		$this->load->model ( 'user_model' );
		if ($this->user_model->delete ( $id )) {
			return_json(TRUE,'','删除成功！');
	    }else{
	    	return_json(FALSE,'','删除失败！');
	    }
	}

	/*
	 * 导入用户信息(一个班级)
	 */
	public function importUser() {
		$class = $this->input->post('class');
		$file = $this->input->post('file');
		$filename=explode("/",$file);
		$tempfile="http://7xj0kd.com2.z0.glb.qiniucdn.com/product/pic/".$filename[2];
		$localfile=getcwd()."/xls/".$filename[2];
		//$file="C:\\Users\\77374\\Desktop\\5.1.xls";
		//$file="http://7xj0kd.com2.z0.glb.qiniucdn.com/product/pic/20160615152659_46065.xls";
		file_put_contents($localfile,file_get_contents($tempfile));
		//
		$this->load->model ( 'user_model' );
		$ext=explode(".",$filename[2]);
		if($ext[1]=='xlsx'){
			$objReader = new PHPExcel_Reader_Excel2007();
		}else{
			 $objReader = new PHPExcel_Reader_Excel5();
		}
		$objPHPExcel = $objReader->load($localfile);
		$sheet = $objPHPExcel->getSheet(0);
		$row = $sheet->getHighestRow();
		for($i=2;$i<=$row;$i++){
			$sno = $sheet->getCell("B".$i)->getValue();
			if(empty($sno)){
				continue;
			}
			$sname = $sheet->getCell("C".$i)->getValue();
			$sname=str_replace(" ","",$sname);
			$user=$this->user_model->find_by_info ( $class,$sno,$sname );
			if(!empty($user)){
				continue;
			}
			$newuser = array (
				'sname' => $sname,
				'class' => $class,
				'sno' => $sno,
				'password' => md5 ( substr($sno,-6) . 'jishibao' )
			);
			$this->user_model->create ( $newuser );
		}
		return_json(TRUE,'','导入成功！');
    }
	/*
	 * 导入用户信息(新)(一个学校)
	 */
	public function importUsers() {
		$school = $this->input->post('school');
		$this->load->model ( 'user_model' );
		$this->load->model ( 'school_model' );
		$classes=$this->school_model->find_class_by_schoolid ($school);
		$file = $this->input->post('file');
		$filename=explode("/",$file);
		$tempfile="http://7xj0kd.com2.z0.glb.qiniucdn.com/product/pic/".$filename[2];
		$localfile=getcwd()."/xls/".$filename[2];
		//$file="C:\\Users\\77374\\Desktop\\5.1.xls";
		//$file="http://7xj0kd.com2.z0.glb.qiniucdn.com/product/pic/20160615152659_46065.xls";
		file_put_contents($localfile,file_get_contents($tempfile));
		//
		$ext=explode(".",$filename[2]);
		if($ext[1]=='xlsx'){
			$objReader = new PHPExcel_Reader_Excel2007();
		}else{
			 $objReader = new PHPExcel_Reader_Excel5();
		}
		$objPHPExcel = $objReader->load($localfile);
		//$count=$objPHPExcel->getSheetCount();
		$num=0;
		foreach($classes as $class){
			$sheet = $objPHPExcel->getSheet($num);
			$row = $sheet->getHighestRow();
			for($i=2;$i<=$row;$i++){
				$sno = $sheet->getCell("B".$i)->getValue();
				if(empty($sno)){
					continue;
				}
				$sname = $sheet->getCell("C".$i)->getValue();
				$sname=str_replace(" ","",$sname);
				$user=$this->user_model->find_by_info ( $class['id'],$sno,$sname );
				if(!empty($user)){
					continue;
				}
				$newuser = array (
					'sname' => $sname,
					'class' => $class['id'],
					'sno' => $sno
				);
				$this->user_model->create ( $newuser );
			}
			$num++;
		}
		return_json(TRUE,'','导入成功！');
    }
	/*
	 * 批量删除用户信息
	 */
	public function deleteUsers() {
		$class = $this->input->post('class');
		$this->load->model ( 'user_model' );
		$this->load->model ( 'olduser_model' );
		$users=$this->user_model->find_by_class ( $class);
		foreach($users as $user){
			$newuser = array (
				'username' => $user['username'],
				'password' => $user['password'],
				'phone' => $user['phone'],
				'pname' => $user['pname'],
				'sname' => $user['sname'],
				'class' => $user['class'],
				'sno' => $user['sno'],
				'balance' => $user['balance'],
				'regist_time' => $user['regist_time'],
			);
			$this->olduser_model->create ( $newuser );
		}
		if ($this->user_model->delete_by_class ( $class )) {
			return_json(TRUE,'','删除成功！');
	    }else{
	    	return_json(FALSE,'','删除失败！');
	    }
    }
	/*
    * 导出无卡学生
    */
    public function exportNoCard(){
        $this->load->model ( 'user_model' );
        $resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->getDefaultRowDimension()->setRowHeight(25);
		$objActSheet->setCellValue ( 'A1', '序号');
		$objActSheet->setCellValue ( 'B1', '姓名');
		$objActSheet->setCellValue ( 'C1', '班级');
		$objActSheet->setCellValue ( 'D1', '学号');
        $data = $this->user_model->find_nocard_users();
        $i=2;
		$row=count($data);
        for ( $j=0;$j<$row;$j++) {
			$objActSheet->setCellValue ( 'A'.$i,  $j+1);
			$objActSheet->setCellValue ( 'B'.$i,  $data[$j]['sname']);
			$objActSheet->setCellValue ( 'C'.$i,  $data[$j]['name'].$data[$j]['gname'].$data[$j]['cname']);
			$objActSheet->setCellValueExplicit ( 'D'.$i, $data[$j]['sno'],PHPExcel_Cell_DataType::TYPE_STRING);
			$i++;
		}
		$styleArray = array(//加入边框
			'borders' => array(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN
				),
			),
		);
		$objActSheet->getStyle('A1:D'.($i-1))->applyFromArray($styleArray);
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 8 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 15 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 35 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 20 );

		$outputFileName = '无卡学生.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		//ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
    }
	/*
    * 导出所有学生
    */
    public function exportAllUser(){
        $this->load->model ( 'user_model' );
        $resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->getDefaultRowDimension()->setRowHeight(25);
		$objActSheet->setCellValue ( 'A1', '序号');
		$objActSheet->setCellValue ( 'B1', '姓名');
		$objActSheet->setCellValue ( 'C1', '班级');
		$objActSheet->setCellValue ( 'D1', '学号');
        $data = $this->user_model->find_all_user();
        $i=2;
		$row=count($data);
        for ( $j=0;$j<$row;$j++) {
			$objActSheet->setCellValue ( 'A'.$i,  $j+1);
			$objActSheet->setCellValue ( 'B'.$i,  $data[$j]['sname']);
			$objActSheet->setCellValue ( 'C'.$i,  $data[$j]['name'].$data[$j]['gname'].$data[$j]['cname']);
			$objActSheet->setCellValueExplicit ( 'D'.$i, $data[$j]['sno'],PHPExcel_Cell_DataType::TYPE_STRING);
			$i++;
		}
		$styleArray = array(//加入边框
			'borders' => array(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN
				),
			),
		);
		$objActSheet->getStyle('A1:D'.($i-1))->applyFromArray($styleArray);
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 8 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 15 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 35 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 20 );

		$outputFileName = '学生列表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		//ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
    }
}
